package algorithm.fft;

public class BinaryFFTCache {
	public final static int WIDTH=8;
	public static Item[] items;  
	//public static int[] elements=new int[WIDTH]; 
	public BinaryFFTCache(){
	}
	public static void buildCache(){
		int upper=(int)(Math.pow(2,WIDTH)+0.5);
		boolean[] b=new boolean[WIDTH];
		items=new Item[upper]; 
		for (int i=0; i<upper; i++){
			toBits(i,b);
			// for debug only
			/*
			String s=this.toString(b); 
			int k2=this.toInt(b);
			int k=Integer.parseInt(s, 2);
			if (k2!=i){
				System.out.println(s+"/"+k2+"/"+i+"/"+k); 
				throw new RuntimeException("error"); 
			}			
			
			if (k!=i){
				throw new RuntimeException("error"); 
			}
			
			System.out.println(k);
			*/
			items[i]=new Item(FFT.fft(b)); 
		}
	}
	public static final Complex[] getCache(boolean[] b){ 
		int index=toInt(b);  
		return items[index].ffted; 
	}
	public static void toBits(int v, boolean[] b){
		for (int i=0; i<WIDTH; i++){ 
			if ((v & 1<<(WIDTH-i-1))>0){
				b[i]=true; 
			}else {
				b[i]=false; 
			}
		} 
	}
	public static String toString(boolean[] b){
		StringBuffer sb=new StringBuffer(); 
		for (int i=0; i<b.length; i++){
			if (b[i]){
				sb.append("1"); 
			}else {
				sb.append("0"); 
			}
		}
		return sb.toString(); 
	}
	public static int toInt(boolean[] b){
		if (b.length!=WIDTH){
			throw new RuntimeException("b.length should be "+WIDTH +" but "+b.length); 
		}
		int val=0; 
		for (int i=0; i<WIDTH; i++){
			if (b[i]==true){ 
				val=val+(1<<(WIDTH-i-1)); 
			}
		}
		return val; 
	}
	public static void main(String[] args){
		int i=1<<7; 
		i=1<<7 & 8;
		BinaryFFTCache b=new BinaryFFTCache(); 
		b.buildCache();
		/*
		boolean[] k=new boolean[WIDTH]; 
		b.toBits(5, k); 
		System.out.println(b.toString(k));
		*/ 
	}
	public static class Item {
		Complex[] ffted=new Complex[BinaryFFTCache.WIDTH];
		public Item(Complex[] c){
			ffted=c; 
		}
	}
}
